import { _ } from 'meteor/underscore';
import { JoinClient } from 'meteor-publish-join';
import { Messages } from '/imports/models/Messages';

Template.messages.onCreated(function () {
  this.limit = new ReactiveVar(15);

  this.autorun(() => {
    this.resultSub = this.subscribe('get.group.messages', { userId: Meteor.userId() }, this.limit.get());

    this.total = JoinClient.get('get.group.messages.counts');
  });
});

Template.messages.onRendered(function () {
  let ps = new PerfectScrollbar("#messages-ps");

  $('#messages-ps').on('ps-y-reach-end', _.throttle(() => {
    let lmt = this.limit.get();

    if (this.total >= lmt) {
      this.limit.set(lmt + 15);
    }
  }, 200));
});

Template.messages.helpers({
  results: function () {
    return Messages.find({}, {
      limit: Template.instance().limit.get()
    });
  },

  loading: function () {
    return !Template.instance().resultSub.ready();
  }
});
